package com.zimi.service;

import cn.hutool.http.HttpUtil;
import com.zimi.bean.SmsInfo;
import com.zimi.util.ShiroUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Service
public class AuthService {

    @Value("${smsurl.url:http://www.qybor.com:8500/shortMessage}")
    private String smsPath;

    @Value("${smsurl.name:ynzimi}")
    private String name;

    @Value("${smsurl.passwd:ynzimi26}")
    private String passwd;

    @Value("${smsurl.port:000}")
    private String port;

    @Value("${smsurl.needstatus:true}")
    private String needstatus;

    public boolean sentNum(String phone) {
        Date currentTime = new Date();
        currentTime.setTime(currentTime.getTime() + 3 * 60 * 1000);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        SmsInfo smsInfo = new SmsInfo();
        smsInfo.setMobile(phone);
        int veryNum = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println(veryNum);
        smsInfo.setContent(String.format("【紫米科技】\r\n%d(果蔬卖卖小程序平台验证码,十五分钟有效)", veryNum));
        smsInfo.setSendTime(df.format(currentTime));
        postSMS(smsInfo);
        Session session = ShiroUtils.getSession();
        session.setAttribute("phone", phone);
        session.setAttribute("veryNum", veryNum);
        session.setAttribute("veryTime", new Date());
        return true;
    }

    public boolean varNum(String phone, String veryNum) {
        Session session = ShiroUtils.getSession();
        String varPhone = (String) session.getAttribute("phone");
        String varNum = (String) session.getAttribute("veryNum");
        session.removeAttribute("phone");
        session.removeAttribute("veryNum");
        session.removeAttribute("veryTime");
        return phone.equals(varPhone) && veryNum.equals(varNum);
    }

    private void postSMS(SmsInfo smsInfo) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", name);
        paramMap.put("passwd", passwd);
        paramMap.put("port", port);
        paramMap.put("needstatus", needstatus);
        paramMap.put("phone", smsInfo.getMobile());
        paramMap.put("msg", smsInfo.getContent());
        paramMap.put("SendTime", smsInfo.getSendTime());
        HttpUtil.post(smsPath, paramMap);
    }
}
